<?php
/***
* @version $Id: class_search.php 336 2007-01-23 08:12:56Z flexiondotorg $
* @copyright (c) 2006 - 2007 Flexion.Org
*            (c) 2006              jelv1 (John Elvin)
*            (c) 2004 - 2006 Tassos Chatzithomaoglou (http://www.psclub.gr)
*            (c) 2004 - 2005 Project Minerva
*            (c) 2001 - 2006 phpBB Group
* @license   http://opensource.org/licenses/gpl-license.php GNU Public License
***/

if (!defined('IN_R3BORN'))
{
	die('Hacking attempt');
}

class search
{
	//The table which holds the content and field by which it realtes to the comment id.
	var $parent_table = '';
	var $parent_field = '';
	var $parent_module = '';
	var $parent_module_id = 0;

	//If this text for a given post in sotre in a different table to the post_id information this supply that table name here.
	var $parent_content_table = '';
	var $parent_subject_field = '';
	var $parent_message_field = '';

	function search($table, $field, $module)
	{
		$this->parent_table = $table;
		$this->parent_field = $field;
		$this->parent_module = $module;
		$this->parent_module_id = getModuleID($module);
	}

	//Define the fields that contain the subject and main message data.
	//If these fields are not in $this->parent_table the pass the table they exist in via $contetn_table
	function set_content_vars($subject_field, $message_field, $content_table = '')
	{
		$this->parent_subject_field = $subject_field;
		$this->parent_message_field = $message_field;

		//If a content table was passed then set parent_content_table accordingly.
		if ($content_table != '')
		{
			$this->parent_content_table = $content_table;
		}
		else
		{
			$this->parent_content_table = $this->parent_table;
		}
	}	

	function clean_words($mode, &$entry, &$stopword_list, &$synonym_list)
	{
		static $drop_char_match =   array('^', '$', '&', '(', ')', '<', '>', '`', '\'', '"', '|', ',', '@', '_', '?', '%', '-', '~', '+', '.', '[', ']', '{', '}', ':', '\\', '/', '=', '#', '\'', ';', '!');
		static $drop_char_replace = array(' ', ' ', ' ', ' ', ' ', ' ', ' ', '',  '',   ' ', ' ', ' ', ' ', '',  ' ', ' ', '',  ' ',  ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ' , ' ', ' ', ' ', ' ',  ' ', ' ');

		$entry = ' ' . strip_tags(strtolower($entry)) . ' ';

		if ( $mode == 'post' )
		{
			// Replace line endings by a space
			$entry = preg_replace('/[\n\r]/is', ' ', $entry);
			// HTML entities like &nbsp;
			$entry = preg_replace('/\b&[a-z]+;\b/', ' ', $entry);
			// Remove URL's
			$entry = preg_replace('/\b[a-z0-9]+:\/\/[a-z0-9\.\-]+(\/[a-z0-9\?\.%_\-\+=&\/]+)?/', ' ', $entry);
			// Quickly remove BBcode.
			$entry = preg_replace('/\[img:[a-z0-9]{10,}\].*?\[\/img:[a-z0-9]{10,}\]/', ' ', $entry);
			$entry = preg_replace('/\[\/?url(=.*?)?\]/', ' ', $entry);
			$entry = preg_replace('/\[\/?[a-z\*=\+\-]+(\:?[0-9a-z]+)?:[a-z0-9]{10,}(\:[a-z0-9]+)?=?.*?\]/', ' ', $entry);
		}
		else if ( $mode == 'search' )
		{
			$entry = str_replace(' +', ' and ', $entry);
			$entry = str_replace(' -', ' not ', $entry);
		}

		//
		// Filter out strange characters like ^, $, &, change "it's" to "its"
		//
		for($i = 0; $i < count($drop_char_match); $i++)
		{
			$entry =  str_replace($drop_char_match[$i], $drop_char_replace[$i], $entry);
		}

		if ( $mode == 'post' )
		{
			$entry = str_replace('*', ' ', $entry);

			// 'words' that consist of <3 or >20 characters are removed.
			$entry = preg_replace('/[ ]([\S]{1,2}|[\S]{21,})[ ]/',' ', $entry);
		}

		if ( !empty($stopword_list) )
		{
			for ($j = 0; $j < count($stopword_list); $j++)
			{
				$stopword = trim($stopword_list[$j]);

				if ( $mode == 'post' || ( $stopword != 'not' && $stopword != 'and' && $stopword != 'or' ) )
				{
					$entry = str_replace(' ' . trim($stopword) . ' ', ' ', $entry);
				}
			}
		}

		if ( !empty($synonym_list) )
		{
			for ($j = 0; $j < count($synonym_list); $j++)
			{
### R3-born - CHANGE (Fix Search Synonym)
#
//				list($replace_synonym, $match_synonym) = split(' ', trim(strtolower($synonym_list[$j])));
				list($match_synonym, $replace_synonym) = split(' ', trim(strtolower($synonym_list[$j])));
#
### R3-born - END CHANGE

				if ( $mode == 'post' || ( $match_synonym != 'not' && $match_synonym != 'and' && $match_synonym != 'or' ) )
				{
					$entry =  str_replace(' ' . trim($match_synonym) . ' ', ' ' . trim($replace_synonym) . ' ', $entry);
				}
			}
		}

		return $entry;
	}

	function split_words($entry) //, $mode = 'post')
	{
		// If you experience problems with the new method, uncomment this block.
		/*
		$rex = ( $mode == 'post' ) ? "/\b([\w��-�][\w��-�']*[\w��-�]+|[\w��-�]+?)\b/" : '/(\*?[a-z0-9��-�]+\*?)|\b([a-z0-9��-�]+)\b/';
		preg_match_all($rex, $entry, $split_entries);

		return $split_entries[1];
		*/
		// Trim 1+ spaces to one space and split this trimmed string into words.
		return explode(' ', trim(preg_replace('#\s+#', ' ', $entry)));
	}

	function add_search_words($mode, $post_id, $post_text, $post_title = '')
	{
		global $db, $root_path, $config, $lang;

		$stopword_array = @file($root_path . 'language/lang_' . $config['default_lang'] . "/search_stopwords.txt");
		$synonym_array = @file($root_path . 'language/lang_' . $config['default_lang'] . "/search_synonyms.txt");

		$search_raw_words = array();
		$search_raw_words['text'] = $this->split_words($this->clean_words('post', $post_text, $stopword_array, $synonym_array));
		$search_raw_words['title'] = $this->split_words($this->clean_words('post', $post_title, $stopword_array, $synonym_array));

		@set_time_limit(0);

		$word = array();
		$word_insert_sql = array();
		while ( list($word_in, $search_matches) = @each($search_raw_words) )
		{
			$word_insert_sql[$word_in] = '';
			if ( !empty($search_matches) )
			{
				for ($i = 0; $i < count($search_matches); $i++)
				{
					$search_matches[$i] = trim($search_matches[$i]);

					if( $search_matches[$i] != '' )
					{
						$word[] = $search_matches[$i];
						if ( !strstr($word_insert_sql[$word_in], "'" . $search_matches[$i] . "'") )
						{
							$word_insert_sql[$word_in] .= ( $word_insert_sql[$word_in] != "" ) ? ", '" . $search_matches[$i] . "'" : "'" . $search_matches[$i] . "'";
						}
					}
				}
			}
		}

		if ( count($word) )
		{
			sort($word);

			$prev_word = '';
			$word_text_sql = '';
			$temp_word = array();
			for($i = 0; $i < count($word); $i++)
			{
				if ( $word[$i] != $prev_word )
				{
					$temp_word[] = $word[$i];
					$word_text_sql .= ( ( $word_text_sql != '' ) ? ', ' : '' ) . "'" . $word[$i] . "'";
				}
				$prev_word = $word[$i];
			}
			$word = $temp_word;

			$check_words = array();
			switch( SQL_LAYER )
			{
				case 'postgresql':
				case 'mssql-odbc':
				case 'oracle':
					$sql = "SELECT word_id, word_text
						FROM " . SEARCH_WORD_TABLE . "
						WHERE word_text IN ($word_text_sql)";
					if ( !($result = $db->sql_query($sql)) )
					{
						message_die(GENERAL_ERROR, 'Could not select words', '', __LINE__, __FILE__, $sql);
					}

					while ( $row = $db->sql_fetchrow($result) )
					{
						$check_words[$row['word_text']] = $row['word_id'];
					}
					break;
			}

			$value_sql = '';
			$match_word = array();
			for ($i = 0; $i < count($word); $i++)
			{
				$new_match = true;
				if ( isset($check_words[$word[$i]]) )
				{
					$new_match = false;
				}

				if ( $new_match )
				{
					switch( SQL_LAYER )
					{
						case 'mysql':
						case 'mysql4':
						case 'mysqli':
							$value_sql .= ( ( $value_sql != '' ) ? ', ' : '' ) . '(\'' . $word[$i] . '\', 0)';
							break;
						case 'mssql':
						case 'mssql-odbc':
							$value_sql .= ( ( $value_sql != '' ) ? ' UNION ALL ' : '' ) . "SELECT '" . $word[$i] . "', 0";
							break;
						default:
							$sql = "INSERT INTO " . SEARCH_WORD_TABLE . " (word_text, word_common)
								VALUES ('" . $word[$i] . "', 0)";
							if( !$db->sql_query($sql) )
							{
								message_die(GENERAL_ERROR, 'Could not insert new word', '', __LINE__, __FILE__, $sql);
							}
							break;
					}
				}
			}

			if ( $value_sql != '' )
			{
				switch ( SQL_LAYER )
				{
					case 'mysql':
					case 'mysql4':
					case 'mysqli':
						$sql = "INSERT IGNORE INTO " . SEARCH_WORD_TABLE . " (word_text, word_common)
							VALUES $value_sql";
						break;
					case 'mssql':
					case 'mssql-odbc':
						$sql = "INSERT INTO " . SEARCH_WORD_TABLE . " (word_text, word_common)
							$value_sql";
						break;
				}

				if ( !$db->sql_query($sql) )
				{
					message_die(GENERAL_ERROR, 'Could not insert new word', '', __LINE__, __FILE__, $sql);
				}
			}
		}

		while( list($word_in, $match_sql) = @each($word_insert_sql) )
		{
			$title_match = ( $word_in == 'title' ) ? 1 : 0;

			if ( $match_sql != '' )
			{
				/*$sql = "INSERT INTO " . SEARCH_MATCH_TABLE . " (parent_id, word_id, title_match)
						SELECT $post_id, word_id, $title_match
						FROM " . SEARCH_WORD_TABLE . "
						WHERE word_text IN ($match_sql)"; */

				$sql = "INSERT INTO " . SEARCH_MATCH_TABLE . " (parent_id, word_id, title_match, parent_field, module_name)
						SELECT $post_id, word_id, $title_match, '" . $this->parent_field . "', '" . $this->parent_module . "'
						FROM " . SEARCH_WORD_TABLE . "
						WHERE word_text IN ($match_sql)";

				if ( !$db->sql_query($sql) )
				{
					message_die(GENERAL_ERROR, 'Could not insert new word matches', '', __LINE__, __FILE__, $sql);
				}
			}
		}

		if ($mode == 'single')
		{
			$this->remove_common('single', 4/10, $word);
		}

		return;
	}

	// how many posts are in the db before or after a specific post_id
	// after/before include the post_id too
	function get_total_posts($mode = 'after', $post_id = 0)
	{
		global $db;

		$sql = "SELECT COUNT(" . $this->parent_field . ") as total_posts FROM " . $this->parent_table . "
			WHERE " . $this->parent_field . " " . (($mode == 'after') ? '>= ' : '<= ' ) . $post_id;

		if ( !($result = $db->sql_query($sql)) )
		{
			message_die(GENERAL_ERROR, 'Could not obtain number of posts', '', __LINE__, __FILE__, $sql);
		}

		$row = $db->sql_fetchrow($result);

		return ( $row['total_posts'] ) ? $row['total_posts'] : 0;
	}

	// get the latest post_id in the forum
	function get_latest_post_id()
	{
		global $db;

		$sql = "SELECT " . $this->parent_field . " FROM " . $this->parent_content_table . "
			ORDER BY " . $this->parent_field . " DESC
			LIMIT 1";

		if ( !($result = $db->sql_query($sql)) )
		{
			message_die(GENERAL_ERROR, 'Could not obtain latest post', '', __LINE__, __FILE__, $sql);
		}

		$row = $db->sql_fetchrow($result);

		return ( $row[$this->parent_field] ) ? $row[$this->parent_field] : 0;
	}

	//
	// Check if specified words are too common now
	//
	function remove_common($mode, $fraction, $word_id_list = array())
	{
		global $db;

		//$sql = "SELECT COUNT(post_id) AS total_posts
		//	FROM " . POSTS_TABLE;
		$sql = "SELECT COUNT(" . $this->parent_field . ") AS total_posts FROM " . $this->parent_table;

		if ( !($result = $db->sql_query($sql)) )
		{
			message_die(GENERAL_ERROR, 'Could not obtain post count', '', __LINE__, __FILE__, $sql);
		}

		$row = $db->sql_fetchrow($result);

		if ( $row['total_posts'] >= 100 )
		{
			$common_threshold = floor($row['total_posts'] * $fraction);

			if ( $mode == 'single' && count($word_id_list) )
			{
				$word_id_sql = '';
				for($i = 0; $i < count($word_id_list); $i++)
				{
					$word_id_sql .= ( ( $word_id_sql != '' ) ? ', ' : '' ) . "'" . $word_id_list[$i] . "'";
				}

				$sql = "SELECT m.word_id
					FROM " . SEARCH_MATCH_TABLE . " m, " . SEARCH_WORD_TABLE . " w
					WHERE w.word_text IN ($word_id_sql)
						AND m.word_id = w.word_id
					GROUP BY m.word_id
					HAVING COUNT(m.word_id) > $common_threshold";
			}
			else
			{
				$sql = "SELECT word_id
					FROM " . SEARCH_MATCH_TABLE . "
					GROUP BY word_id
					HAVING COUNT(word_id) > $common_threshold";
			}

			if ( !($result = $db->sql_query($sql)) )
			{
				message_die(GENERAL_ERROR, 'Could not obtain common word list', '', __LINE__, __FILE__, $sql);
			}

			$common_word_id = '';
			while ( $row = $db->sql_fetchrow($result) )
			{
				$common_word_id .= ( ( $common_word_id != '' ) ? ', ' : '' ) . $row['word_id'];
			}
			$db->sql_freeresult($result);

			if ( $common_word_id != '' )
			{
				$sql = "UPDATE " . SEARCH_WORD_TABLE . "
					SET word_common = " . TRUE . "
					WHERE word_id IN ($common_word_id)";
				if ( !$db->sql_query($sql) )
				{
					message_die(GENERAL_ERROR, 'Could not delete word list entry', '', __LINE__, __FILE__, $sql);
				}

				$sql = "DELETE FROM " . SEARCH_MATCH_TABLE . "
					WHERE word_id IN ($common_word_id)";
				if ( !$db->sql_query($sql) )
				{
					message_die(GENERAL_ERROR, 'Could not delete word match entry', '', __LINE__, __FILE__, $sql);
				}
			}
		}

		return;
	}

	function remove_search_post($post_id_sql)
	{
		global $db;

		$words_removed = false;

		switch ( SQL_LAYER )
		{
			case 'mysql':
			case 'mysql4':
			case 'mysqli':
				$sql = "SELECT word_id
					FROM " . SEARCH_MATCH_TABLE . "
					WHERE parent_id IN ($post_id_sql)
					AND module_name = '" . $this->parent_module . "'
					GROUP BY word_id";
				if ( $result = $db->sql_query($sql) )
				{
					$word_id_sql = '';
					while ( $row = $db->sql_fetchrow($result) )
					{
						$word_id_sql .= ( $word_id_sql != '' ) ? ', ' . $row['word_id'] : $row['word_id'];
					}

					$sql = "SELECT word_id
						FROM " . SEARCH_MATCH_TABLE . "
						WHERE word_id IN ($word_id_sql)
						AND module_name = '" . $this->parent_module . "'
						GROUP BY word_id
						HAVING COUNT(word_id) = 1";
					if ( $result = $db->sql_query($sql) )
					{
						$word_id_sql = '';
						while ( $row = $db->sql_fetchrow($result) )
						{
							$word_id_sql .= ( $word_id_sql != '' ) ? ', ' . $row['word_id'] : $row['word_id'];
						}

						if ( $word_id_sql != '' )
						{
							$sql = "DELETE FROM " . SEARCH_WORD_TABLE . "
								WHERE word_id IN ($word_id_sql)";
							if ( !$db->sql_query($sql) )
							{
								message_die(GENERAL_ERROR, 'Could not delete word list entry', '', __LINE__, __FILE__, $sql);
							}

							$words_removed = $db->sql_affectedrows();
						}
					}
				}
				break;

			default:
				$sql = "DELETE FROM " . SEARCH_WORD_TABLE . "
					WHERE word_id IN (
						SELECT word_id
						FROM " . SEARCH_MATCH_TABLE . "
						WHERE word_id IN (
							SELECT word_id
							FROM " . SEARCH_MATCH_TABLE . "
							WHERE parent_id IN ($post_id_sql)
							AND module_name = '" . $this->parent_module . "'
							GROUP BY word_id
						)
						GROUP BY word_id
						HAVING COUNT(word_id) = 1
					)";
				if ( !$db->sql_query($sql) )
				{
					message_die(GENERAL_ERROR, 'Could not delete old words from word table', '', __LINE__, __FILE__, $sql);
				}

				$words_removed = $db->sql_affectedrows();

				break;
		}

		$sql = "DELETE FROM " . SEARCH_MATCH_TABLE . "
			WHERE parent_id IN ($post_id_sql)
			AND module_name = '" . $this->parent_module . "'";
		if ( !$db->sql_query($sql) )
		{
			message_die(GENERAL_ERROR, 'Error in deleting post', '', __LINE__, __FILE__, $sql);
		}

		return $words_removed;
	}

	// get the last rebuild_session_id
	function get_last_rebuild_session_id()
	{
		global $db;

		$sql = "SELECT rebuild_session_id FROM " . SEARCH_REBUILD_TABLE . "
			WHERE module_name = '" . $this->parent_module . "'
			ORDER BY rebuild_session_id DESC
			LIMIT 1";

		if ( !($result = $db->sql_query($sql)) )
		{
			message_die(GENERAL_ERROR, 'Could not obtain rebuild session id', '', __LINE__, __FILE__, $sql);
		}

		$row = $db->sql_fetchrow($result);

		return ( $row['rebuild_session_id'] ) ? $row['rebuild_session_id'] : 0;
	}


	// get some or all of the rebuild details of a specific session or of the last session
	// $id is the id or the 'last' id
	// $details is one of the fields or 'all' of them
	function get_rebuild_session_details($id, $details = 'all')
	{
		global $db;

		if ( $id != 'last' )
		{
			$sql = "SELECT * FROM " . SEARCH_REBUILD_TABLE . "
				WHERE rebuild_session_id = $id
				AND module_name = '" . $this->parent_module . "'";
		}
		else
		{
			$sql = "SELECT * FROM " . SEARCH_REBUILD_TABLE . "
				WHERE module_name = '" . $this->parent_module . "'
				ORDER BY rebuild_session_id DESC
				LIMIT 1";
		}

		if ( !($result = $db->sql_query($sql)) )
		{
			message_die(GENERAL_ERROR, 'Could not obtain rebuild details', '', __LINE__, __FILE__, $sql);
		}

		$row = $db->sql_fetchrow($result);

		if ( !empty($row) )
		{
			$return_details = ( $details == 'all') ? $row : $row[$details];

			return ( !empty($return_details) ) ? $return_details : 0;
		}
		else
		{
			return 0;
		}
	}

	// get the number of processed posts in the last session or in all sessions
	//
	// 'total' to get the sum of posts of all sessions
	// 'session' to get the posts of the last session
	function get_processed_posts($mode = 'total')
	{
		global $db;

		if ( $mode == 'total' )
		{
			$sql = "SELECT SUM(session_posts) as posts FROM " . SEARCH_REBUILD_TABLE . " WHERE module_name = '" . $this->parent_module . "'";
		}
		else	// $mode = session
		{
			$sql = "SELECT session_posts as posts FROM " . SEARCH_REBUILD_TABLE . "
			WHERE rebuild_session_id = " . $this->get_last_rebuild_session_id() . " AND module_name = '" . $this->parent_module . "'";
		}

		if ( !($result = $db->sql_query($sql)) )
		{
			message_die(GENERAL_ERROR, 'Could not obtain number of posts', '', __LINE__, __FILE__, $sql);
		}

		$row = $db->sql_fetchrow($result);

		return ( $row['posts'] ) ? $row['posts'] : 0;
	}
	// clear the search tables
	function clear_search_tables($clear_search)
	{
		global $db;

		// initialize our own table
		$sql = "DELETE FROM " . SEARCH_REBUILD_TABLE . " WHERE module_name = '" . $this->parent_module ."'";

		if( !$db->sql_query($sql) )
		{
			message_die(GENERAL_ERROR, 'Could not delete search rebuild table', '', __LINE__, __FILE__, $sql);
		}

		// initialize (clear) all 3 r3born_search tables
		if ( $clear_search )
		{
			$table_ary = array(SEARCH_TABLE, SEARCH_WORD_TABLE, SEARCH_MATCH_TABLE);

			foreach ($table_ary as $table)
			{
				$sql = (( $clear_search == 1 ) ? "DELETE FROM " : "TRUNCATE TABLE " ) . $table;// . " WHERE module_name = '" . $this->parent_module . "'";

				if( !$db->sql_query($sql) )
				{
					message_die(GENERAL_ERROR, 'Could not delete search table', '', __LINE__, __FILE__, $sql);
				}
			}
		}
	}
}

function get_db_sizes()
{
	global $db, $table_prefix, $dbname;

	// some code taken from admin/index.php
	//
	// DB size ... MySQL only
	//
	// This code is heavily influenced by a similar routine
	// in phpMyAdmin 2.2.0
	//
	if( preg_match("/^mysql/", SQL_LAYER) )
	{
		$sql = "SELECT VERSION() AS mysql_version";
		if($result = $db->sql_query($sql))
		{
			$row = $db->sql_fetchrow($result);
			$version = $row['mysql_version'];

			if( preg_match("/^(3\.23|4\.|5\.)/", $version) )
			{
				$db_name = ( preg_match("/^(3\.23\.[6-9])|(3\.23\.[1-9][1-9])|(4\.)|(5\.)/", $version) ) ? "`$dbname`" : $dbname;

				$sql = "SHOW TABLE STATUS
					FROM " . $db_name;

				if($result = $db->sql_query($sql))
				{
					$tabledata_ary = $db->sql_fetchrowset($result);

					$db_size = 0;
					$search_size = 0;	// added

					for($i = 0; $i < count($tabledata_ary); $i++)
					{
						if( $tabledata_ary[$i]['Type'] != "MRG_MyISAM" )
						{
							if( $table_prefix != "" )
							{
								if( strstr($tabledata_ary[$i]['Name'], $table_prefix) )
								{
									$db_size += $tabledata_ary[$i]['Data_length'] + $tabledata_ary[$i]['Index_length'];
								}
							}
							else
							{
								$db_size += $tabledata_ary[$i]['Data_length'] + $tabledata_ary[$i]['Index_length'];
							}

							// calculate the size of the search tables only
							if ( $tabledata_ary[$i]['Name'] == SEARCH_WORD_TABLE || $tabledata_ary[$i]['Name'] == SEARCH_MATCH_TABLE )
							{
								$search_size += $tabledata_ary[$i]['Data_length'] + $tabledata_ary[$i]['Index_length'];
							}
						}
					}
				} // Else we couldn't get the table status.
			}
			else
			{
				$db_size = '';			// changed
				$search_size = '';	// changed
			}
		}
		else
		{
			$db_size = '';			// changed
			$search_size = '';	// changed
		}
	}
	else if( preg_match("/^mssql/", SQL_LAYER) )
	{
		$sql = "SELECT ((SUM(size) * 8.0) * 1024.0) as dbsize
			FROM sysfiles";

		if( $result = $db->sql_query($sql) )
		{
			$db_size = ( $row = $db->sql_fetchrow($result) ) ? intval($row['dbsize']) : '';	// changed
			$search_size = '';	// added
		}
		else
		{
			$db_size = '';			// changed
			$search_size = '';	// added
		}
	}
	else
	{
		$db_size = '';				// changed
		$search_size = '';		// added
	}

	return array($db_size, $search_size);
}

// convert numeric value to x Bytes string
function create_db_size($db_size)
{
	global $lang;

	if ( $db_size != '' && is_numeric($db_size) )
	{
		if( $db_size >= 1048576 )
		{
			$db_size = sprintf("%.2f MB", ( $db_size / 1048576 ));
		}
		else if( $db_size >= 1024 )
		{
			$db_size = sprintf("%.2f KB", ( $db_size / 1024 ));
		}
		else
		{
			$db_size = sprintf("%.2f ".$lang['Bytes'], $db_size);
		}
	}
	else
	{
		$db_size = $lang['Not_available'];
	}

	return $db_size;
}

// convert time values (seconds) to "number of days, hours, minutes and seconds"
function create_time($seconds)
{
	global $lang;

	$days = 0;
	$hours = 0;
	$minutes = 0;

	while ( $seconds >= 60 )
	{
		if ( $seconds >= 86400 )
		{
			// more than 1 day
			$days = floor($seconds / 86400);
			$seconds = $seconds - ($days * 86400);
		}
		elseif ( $seconds >= 3600 )
		{
			// more than 1 hour
			$hours = floor($seconds / 3600);
			$seconds = $seconds - ($hours * 3600);
		}
		elseif ( $seconds >= 60 )
		{
			$minutes = floor($seconds / 60);
			$seconds = $seconds - ($minutes * 60);
		}
	}

	return sprintf("%02d", $days).' '.$lang['days'].', '.sprintf("%02d", $hours).' '.$lang['hours'].', '.sprintf("%02d", $minutes).' '.$lang['minutes'].', '.sprintf("%02d", $seconds).' '.$lang['seconds'];
}

// Create the percent color
// We use an array with the color percent limits.
// One color stays constantly at FF when the percent is between its limits
// and we adjust the other 2 accordingly to percent, from 200 to 0.
// We limit the result to 200, in order to avoid getting close to white (255).
function create_percent_color($percent)
{
	$percent_ary = array('g' => array(0,50),
								'b' => array(51,85),
								'r' => array(86,100)
								);

	foreach ($percent_ary as $key => $value)
	{
		if ( $percent <= $value[1] )
		{
			$percent_color = create_color($key, round(200-($percent-$value[0])*(200/($value[1]-$value[0]))));
			break;
		}
	}

	return $percent_color;
}

// create the hex representation of color
function create_color($mode, $code)
{
	return (($mode == 'r') ? 'FF': sprintf("%02X", $code)) . (($mode == 'g') ? 'FF': sprintf("%02X", $code)) . (($mode == 'b') ? 'FF': sprintf("%02X", $code));
}

// create the percent bar & box
function create_percent_box($box, $percent_color, $percent_width)
{
	global $template;

	$template->set_filenames(array(
		'percent_box' => 'rebuild_search_percent.tpl')
	);

	$template->assign_vars(array(
		'PERCENT_COLOR'	=> $percent_color,
		'PERCENT_WIDTH'	=> round($percent_width)
		)
	);

	if ( $box == 'session' )
	{
		$template->assign_var_from_handle('SESSION_PERCENT_BOX', 'percent_box');
	}
	else
	{
		$template->assign_var_from_handle('TOTAL_PERCENT_BOX', 'percent_box');
	}

	return;
}

// enable/disable the board
function change_board_status($state = 'enable')
{
	global $db;

	$sql = "UPDATE " . CONFIG_TABLE . "
		SET config_value = " . ( ( $state == 'enable' ) ? 0 : 1 ) . "
		WHERE config_name = 'board_disable'";

	if ( !$db->sql_query($sql) )
	{
		message_die(GENERAL_ERROR, 'Could not disable/enable board', '', __LINE__, __FILE__, $sql);
	}
}

//
// Color search
//
function color_search()
{
	global $template, $lang, $root_path;

	$template->set_filenames(array(
		'search_color' => 'search_color.tpl')
	);

	$template->assign_vars(array(
		'L_WEB_SAFE' => $lang['color_web_safe'],
		'L_WINDOWS_SYSTEM' => $lang['color_windows_system'],
		'L_GREY_SCALE' => $lang['color_grey_scale'],
		'L_MAC_OS' => $lang['color_mac_os'],
		'PAGE_TITLE' => $lang['color_search'],
		'S_CONTENT_DIRECTION' => $lang['DIRECTION'],
		'S_CONTENT_ENCODING' => $lang['ENCODING'],
		)
	);

	$template->pparse('search_color');

	return;
}

//
// Username search
//
function username_search($search_match)
{
	global $db, $config, $template, $lang, $images, $theme, $phpEx, $root_path;
	//global $starttime;

	$username_list = '';
	if ( !empty($search_match) )
	{
		$username_search = preg_replace('/\*/', '%', r3born_clean_username($search_match));

		$sql = "SELECT username
			FROM " . USERS_TABLE . "
			WHERE username LIKE '" . str_replace("\'", "''", $username_search) . "' AND user_id <> " . ANONYMOUS . "
			ORDER BY username";
		if ( !($result = $db->sql_query($sql)) )
		{
			message_die(GENERAL_ERROR, 'Could not obtain search results', '', __LINE__, __FILE__, $sql);
		}

		if ( $row = $db->sql_fetchrow($result) )
		{
			do
			{
				$username_list .= '<option value="' . $row['username'] . '">' . $row['username'] . '</option>';
			}
			while ( $row = $db->sql_fetchrow($result) );
		}
		else
		{
			$username_list .= '<option>' . $lang['No_match']. '</option>';
		}
		$db->sql_freeresult($result);
	}

	page_header($lang['Search'], true);

	$template->set_filenames(array(
		'search_user_body' => 'search_username.tpl')
	);

	$template->assign_vars(array(
		'USERNAME' => (!empty($search_match)) ? r3born_clean_username($search_match) : '',

		'L_CLOSE_WINDOW' => $lang['Close_window'],
		'L_SEARCH_USERNAME' => $lang['Find_username'],
		'L_UPDATE_USERNAME' => $lang['Select_username'],
		'L_SELECT' => $lang['Select'],
		'L_SEARCH' => $lang['Search'],
		'L_SEARCH_EXPLAIN' => $lang['Search_author_explain'],
		'L_CLOSE_WINDOW' => $lang['Close_window'],

		'U_SEARCH_JS' => $root_path . 'javascript/search.js',

		'S_USERNAME_OPTIONS' => $username_list,
		'S_SEARCH_ACTION' => append_sid("search.$phpEx?mode=searchuser"))
	);

	if ( $username_list != '' )
	{
		$template->assign_block_vars('switch_select_name', array());
	}

	$template->pparse('search_user_body');

	page_footer(true);

	return;
}

?>